package com.qust.endecryptionmanager.controller;

import com.alibaba.fastjson2.JSON;
import com.qust.endecryptionmanager.pojo.AlgorithmInfo;
import com.qust.agreement.result.Result;
import com.qust.endecryptionmanager.service.AlgorithmService;
import com.qust.endecryptionmanager.utils.DateUtils;
import jdk.nashorn.internal.objects.annotations.Getter;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Map;
import java.util.Set;
@Log4j2
@RestController
@RequestMapping("/algorithmController")
public class AlgorithmController {
    private final AlgorithmService algorithmService;
    private final String prefix = "EnDecryption-manager/src/main/resources/lib/";
    public AlgorithmController(AlgorithmService algorithmService) {
        this.algorithmService = algorithmService;
    }


    /**
     *  上传算法jar包,保存和创建算法实例,并且将算法实例传到server集群中
     * @return
     * @throws IOException
     */
    @PostMapping("/")
    public Result<?> uploadJar(@RequestParam("file") MultipartFile multipartFile,@RequestParam("fileName") String name,
                               @RequestParam("classPath") String classPath,@RequestParam("description") String description) throws Exception {
        byte[] fileBytes = multipartFile.getBytes();
        AlgorithmInfo algorithmInfo = new AlgorithmInfo();
        algorithmInfo.setJarPath(prefix+name+".jar");
        algorithmInfo.setName(name);
        algorithmInfo.setDescription(description);
        algorithmInfo.setClassPath(classPath);
        algorithmService.uploadInfo(algorithmInfo,fileBytes);
        return Result.success("算法传输中,请稍等几分钟使用新算法");
    }

    /**
     * 追赶缺失的资源
     * @param map
     * @return
     */
    @PostMapping("/catchUp")
    public Result<?> catchUp(@RequestBody Map<String,String> map){
        log.info("{}",map);
        Set<Integer> missing = JSON.parseObject(map.get("missing"), Set.class);
        algorithmService.resourceScheduling(map.get("address"),missing);
        return null;
    }

    @DeleteMapping("/{name}")
    public Result<?> deleteJar(@PathVariable String name){
        algorithmService.deleteJar(name);
        return Result.success(null);
    }

    @GetMapping("/")
    public Result<?> checkIntegrity(){
        return Result.success(algorithmService.checkIntegrity());
    }
}
